package com.zixue.heima.helloNetty.EventLoopGroopDemo;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * @ClassName : NettyFuture
 * @Description : TODO
 * @Author : chunxiong
 * @Date : 2025/5/8 00:32
 * @Version 1.0
 */
@Slf4j
public class NettyFuture {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        EventLoop eventLoop = group.next();
        Future<Integer> future = eventLoop.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(2000);
                log.info("2秒耗时 执行计算");
                return 100;
            }
        });
        //主线程如何通信这个线程呢？future对象
        //1同步方式
//        log.info("等待结果");
//        Integer integer = future.get();// 阻塞 同步等待别人线程执行完，我拿结果
//        log.info("结果：" + integer);

        //netty更强支持异步方式
        //2。异步方式
        future.addListener(new GenericFutureListener<Future<? super Integer>>() {
            @Override
            public void operationComplete(Future<? super Integer> future) throws Exception {
                //通过future拿结果 get阻塞  getNow不阻塞  回调肯定有结果 这里是Nio线程拿到结果， 不是住线程
                log.info("接受结果:{}",future.getNow());
            }
        });
    }
}
